// pages/index/index.js
const app = getApp()
const db = wx.cloud.database()
const MAX_LIMIT = 10

Page({
  data: {
    articles: [],
    page: 1,
    hasMore: true,
    loading: false,
    defaultCover: '/images/default-cover.png'
  },

  onLoad: function (options) {
    this.loadArticles(true)
  },

  onPullDownRefresh: function () {
    this.loadArticles(true)
  },

  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadArticles()
    }
  },

  // 加载文章列表
  loadArticles: function (refresh = false) {
    if (this.data.loading) return
    
    this.setData({
      loading: true
    })

    const page = refresh ? 1 : this.data.page
    
    wx.cloud.callFunction({
      name: 'getArticles',
      data: {
        page
      }
    }).then(res => {
      // 检查返回结果是否正确
      if (!res.result || res.result.code !== 0 || !res.result.data) {
        throw new Error(res.result?.message || '获取文章列表失败')
      }
      
      const { data, total, page, pageSize } = res.result
      
      // 确保data是数组
      if (!Array.isArray(data)) {
        throw new Error('文章数据格式错误')
      }
      
      // 格式化时间
      const articles = data.map(item => {
        return {
          ...item,
          createTime: app.formatTime(item.createTime)
        }
      })
      
      this.setData({
        articles: refresh ? articles : [...this.data.articles, ...articles],
        page: page + 1,
        hasMore: page * pageSize < total,
        loading: false
      })

      if (refresh) {
        wx.stopPullDownRefresh()
      }
    }).catch(err => {
      console.error('获取文章列表失败', err)
      this.setData({
        loading: false
      })
      
      if (refresh) {
        wx.stopPullDownRefresh()
      }
      
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    })
  },

  // 跳转到文章详情
  goToArticle: function (e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/article/index?id=${id}`
    })
  }
})